<script setup>
import patient from '@/api/patient';
import {reactive, ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus'
import {Plus, Refresh, Search} from "@element-plus/icons-vue";
import {tokenStore} from "@/store";
// 获取 token store 实例
const tokenStoreInstance = tokenStore()
// 获取 token 值
const token = tokenStoreInstance.token
const patients = ref([]);

// 分页信息
const pageInfo = reactive({
  page: 1,
  limit: 5,
  total: 0,
})

// 获取患者列表
loadPatient();

// 页码和页面大小更新
function loadPatient() {
  patient.search(pageInfo).then(result => {
    console.log(result)
    patients.value = result.data.records;
    pageInfo.total = result.data.total;
  });
}

// 添加的相关操作
const addVisible = ref(false);

const addPatient = ref({roles: []});

function showAdd() {
  addVisible.value = true;    // 显示添加窗口
}

function handleAdd() {
  patient.add(addPatient.value).then(result => {
    if (result.code == 200) {
      ElMessage({message: '新添加病人成功！', type: 'success'})
      addVisible.value = false;
      addPatient.value = {roles: []};
    } else {
      ElMessage.error(result.data);
    }
    // 刷新表格数据
    loadPatient();
  });
}
// 上传图片
function getUploadURL() {
  return  '/api/upload';
}
function handleAddAvatarSuccess(response, uploadFile) {
  addPatient.value.photo = response.data;
}
//修改头像
function handleEditAvatarSuccess(response, uploadFile) {
  editPatient.value.photo = response.data;
}
//获得图片的URL
function getImgUrl(url) {
  return url;
}


// 编辑的操作
const editVisible = ref(false);

const editPatient = ref({});

// function showEdit(row) {
//   editVisible.value = true;
//   editPatient.value = JSON.parse(JSON.stringify(row));   // 深拷贝
//   editPatient.value.password = "";
// }

function handleEdit() {
  patient.edit(editPatient.value).then(result => {
    if (result.code == 200) {
      ElMessage({message: '编辑病人信息成功！', type: 'success'})
      editVisible.value = false;
    } else {
      ElMessage.error(result.data);
    }
    // 刷新表格数据
    loadPatient();
  });
}

function onSearch() {
  pageInfo.page = 1;
  loadPatient();
}

// 状态区分
function getStatusTagType(status) {
  switch (status) {
    case '正常':
    case 'Normal':
      return 'success';
    case '已挂号':
    case 'Registered':
      return 'primary';
    case '就诊中':
    case 'In Treatment':
      return 'warning';
    case '已完成':
    case 'Completed':
      return 'info';
    case '已取消':
    case 'Cancelled':
      return 'danger';
    default:
      return 'info';
  }
}

//密码验证
const passwordVisible = ref(false);
const verifyPassword = ref('');
const currentEditRow = ref(null);

// 显示密码验证弹窗
function showEdit(row) {
  currentEditRow.value = row;
  verifyPassword.value = '';
  passwordVisible.value = true;
}
function resetSearch() {
  // 清空搜索条件
  pageInfo.name = '';
  pageInfo.phone = '';

  // 重置页码
  pageInfo.page = 1;

  // 重新加载数据
  loadPatient();
}
//验证密码
function verifyEditPassword() {

  patient.verifyPassword({
    id: currentEditRow.value.id,
    password: verifyPassword.value
  }).then(result => {
    if (result.code == 200) {
      // 密码验证成功，显示编辑弹窗
      passwordVisible.value = false;
      editPatient.value = JSON.parse(JSON.stringify(currentEditRow.value));
      editPatient.value.password = "";
      editVisible.value = true;
      ElMessage.success("验证成功")
    } else {
      ElMessage.error(result.msg || '密码错误');
    }
  });
}
const rules=ref({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { min: 11, max: 11, message: '长度为11位', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { min: 18, max: 18, message: '长度为18位', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
})
</script>

<template>
  <div class="content">
    <el-form :model="pageInfo" :inline="true">
      <el-form-item label="名字" :label-width="60">
        <el-input v-model="pageInfo.name" placeholder="请输入患者姓名"/>
      </el-form-item>
      <el-form-item label="电话" :label-width="60">
        <el-input v-model="pageInfo.phone" placeholder="请输入患者电话"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">
          <el-icon>
            <Search></Search>
          </el-icon>
        </el-button>
        <el-button @click="resetSearch" style="margin-left: 10px;">
          <el-icon>
            <Refresh></Refresh>
          </el-icon>
        </el-button>
      </el-form-item>
    </el-form>
    <div class="bar">
      <el-button type="success" @click="showAdd">新增患者</el-button>
    </div>
    <el-table :data="patients" :stripe="true" :border="true" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" fixed/>
      <el-table-column prop="name" label="姓名" width="80" fixed/>
      <el-table-column prop="photo" label="照片" width="150" fixed>
        <template #default="scope">
          <img :src="getImgUrl(scope.row.photo)" class="circular-photo" alt=""/>
        </template>
      </el-table-column>
      <el-table-column prop="birthday" label="生日" width="180"/>
      <el-table-column prop="idCard" label="身份证号" width="180"/>
      <el-table-column prop="phone" label="手机号" width="180"/>

      <el-table-column prop="status" label="状态" width="180">
        <template #default="scope">
          <el-tag
              :type="getStatusTagType(scope.row.status)"
              effect="dark"
              size="small">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180"/>
      <el-table-column prop="updateTime" label="最近修改时间" width="180"/>
      <el-table-column prop="createUser" label="创建人" width="180"/>
      <el-table-column prop="updateUser" label="修改人" width="180"/>
      <el-table-column prop="email" label="邮箱" width="180"/>
      <el-table-column label="操作" fixed="right" width="180">
        <template #default="scope" >
          <el-button size="small" type="success"
                     @click="showEdit(scope.row)">编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="page" v-model:current-page="pageInfo.page" v-model:page-size="pageInfo.limit"
                   :total="pageInfo.total" :page-sizes="[5, 10, 20, 50]" :background="true"
                   layout="total, sizes, prev, pager, next, jumper" @change="loadPatient"/>
  </div>

  <!-- 添加的弹窗 -->
  <el-dialog v-model="addVisible" title="添加新的患者" width="500">
    <el-form :model="addPatient" :rules="rules">
      <el-form-item label="姓名" :label-width="80" prop="name" >
        <el-input v-model="addPatient.name" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="身份证号" :label-width="80" prop="idCard">
        <el-input v-model="addPatient.idCard" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="手机号" :label-width="80" prop="phone">
        <el-input v-model="addPatient.phone" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="邮箱" :label-width="80" prop="email">
        <el-input v-model="addPatient.email" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="生日" :label-width="80">
        <el-date-picker
            v-model="addPatient.birthday"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="照片" :label-width="80">
        <el-upload
            class="avatar-uploader"
            :action="getUploadURL()"
            :headers="{'token': token}"
            :show-file-list="false"
            :on-success="handleAddAvatarSuccess"
        >
          <img v-if="addPatient.photo" :src="getImgUrl(addPatient.photo)" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
     <el-form-item label="状态" :label-width="80">
  <el-select v-model="addPatient.status" placeholder="请选择状态">
    <el-option label="正常" value="正常"></el-option>
    <el-option label="已挂号" value="已挂号"></el-option>
    <el-option label="就诊中" value="就诊中"></el-option>
    <el-option label="已完成" value="已完成"></el-option>
    <el-option label="已取消" value="已取消"></el-option>
  </el-select>
</el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdd">
          创建
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 编辑的弹窗 -->
  <el-dialog v-model="editVisible" title="修改患者信息" width="500">
    <el-form :model="editPatient" :rules="rules">
      <el-form-item label="姓名" :label-width="80" prop="name">
        <el-input v-model="editPatient.name" autocomplete="off" disabled/>
      </el-form-item>
      <el-form-item label="身份证号" :label-width="80" prop="idCard">
        <el-input v-model="editPatient.idCard" autocomplete="off" disabled/>
      </el-form-item>
      <el-form-item label="手机号" :label-width="80" prop="phone">
        <el-input v-model="editPatient.phone" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="邮箱" :label-width="80" prop="email">
        <el-input v-model="editPatient.email" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="生日" :label-width="80">
        <el-date-picker
            v-model="editPatient.birthday"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="照片" :label-width="80">
        <el-upload
            class="avatar-uploader"
            :action="getUploadURL()"
            :headers="{'token': token}"
            :show-file-list="false"
            :on-success="handleEditAvatarSuccess"
        >
          <img v-if="editPatient.photo" :src="getImgUrl(editPatient.photo)" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <!-- 添加密码修改字段 -->
      <el-form-item label="新密码" :label-width="80">
        <el-input
            v-model="editPatient.password"
            type="password"
            placeholder="留空则不修改密码"
            autocomplete="new-password"
        />
      </el-form-item>
      <el-form-item label="状态" :label-width="80">
        <el-select v-model="editPatient.status" placeholder="请选择状态">
          <el-option label="正常" value="正常"></el-option>
          <el-option label="已挂号" value="已挂号"></el-option>
          <el-option label="就诊中" value="就诊中"></el-option>
          <el-option label="已完成" value="已完成"></el-option>
          <el-option label="已取消" value="已取消"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEdit">
          编辑
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 密码验证弹窗 -->
<el-dialog v-model="passwordVisible" title="请输入密码验证身份" width="400">
  <el-form>
    <el-form-item label="密码" :label-width="80">
      <el-input
        v-model="verifyPassword"
        type="password"
        show-password
        placeholder="请输入患者密码"
        @keyup.enter="verifyEditPassword"
      />
    </el-form-item>
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="passwordVisible = false">取消</el-button>
      <el-button type="primary" @click="verifyEditPassword">验证</el-button>
    </div>
  </template>
</el-dialog>

</template>

<style scoped>
/* 添加圆形照片样式 */
.circular-photo {
  width: 90px;
  height: 90px;
  border-radius: 50%;
  object-fit: cover;
  display: block;
  margin: 5px auto;
}
</style>